#coding=utf-8
# Create your views here.
from django.http import HttpResponse,HttpResponseRedirect
from umwork.models import *
from umwork.forms import *
from django.shortcuts import render_to_response
import sys,os
import subprocess
from umework import settings

def send_mail(to_user,sub,content):
    import smtplib
    from email.mime.text import MIMEText
    mailconfig = Config.objects.order_by("-id")[0]
    smtp = mailconfig.mailsmtp
    user = mailconfig.mailuser
    passwd = mailconfig.mailpass
    from_user = mailconfig.mailfrom
    msg = MIMEText(content.encode('utf-8'))
    msg['Subject'] = sub
    msg['From'] = from_user
    msg['To'] = to_user
    s = smtplib.SMTP()
    s.connect(smtp)
    s.login(user,passwd)
    s.sendmail(from_user,to_user,msg.as_string())
    s.close()
    
def register(request):
    try:
        cleckuser = User.objects.order_by("-id")[0].id
    except:
        cleckuser = ' '
    print cleckuser
    if cleckuser:
        if request.method == "POST":
            fr = UserForm(request.POST)
            if fr.is_valid():
                User.objects.create(
                user = fr.cleaned_data['user'],
                passwd = fr.cleaned_data['passwd'],
                name = fr.cleaned_data['name'],
                post = "运维部",
                phone = fr.cleaned_data['phone'],
                email = fr.cleaned_data['email'],
                qq = fr.cleaned_data['qq'],
                permissions = "运维经理",  #使用此request后，在forms.py中，不可出现此字段，否则会出错
                )   
                return HttpResponseRedirect('/login.html')
            else:
                return HttpResponse('输入有误')
        else:
            fr = UserForm()
        return render_to_response('register.html',locals())
    else:
        return HttpResponse('此页已失效！')
    
    
def host(request):
    username = request.session.get('username',None)    #获取登陆的用户名
    if username != None:   #假如username 不等于 none，即是用户处于登陆状态，则执行下面的请求权限的语句，如果没有登陆，则不请求权限
        userpermissions = User.objects.get(name = username).permissions  #获取登陆的用户权限
    else:
        return HttpResponseRedirect('/login.html')   #如果用户没有登陆此系统，则跳转到登陆页
    iplist = IP.objects.all()    #获取所有的IP信息，最后通过下面代码发送前端，端用for把这些信息遍历出来
    return render_to_response('host.html',locals())
    
def hostadd(request):
    username = request.session.get('username',None)
    group_list = IpGroup.objects.all()
    if request.method == "POST":
        fr = HostAddForm(request.POST)
        if fr.is_valid():
            IP.objects.create(
            ip = fr.cleaned_data['ip'],
            port = fr.cleaned_data['port'],
            user = fr.cleaned_data['user'],
            passwd = fr.cleaned_data['passwd'],
            protocol_type = fr.cleaned_data['protocol_type'],
            hostname = fr.cleaned_data['hostname'],
            system = fr.cleaned_data['system'],
            server_models = fr.cleaned_data['server_models'],
            cpu = fr.cleaned_data['cpu'],
            cpumun = fr.cleaned_data['cpumun'],
            hmem = fr.cleaned_data['hmem'],
            vmem = fr.cleaned_data['vmem'],
            disk = fr.cleaned_data['disk'],
            alias = fr.cleaned_data['alias'],
            group = request.POST.get(u'select','末分组'),
            )
            msg = '主机添加成功！'
            return render_to_response('msg.html',locals())

    else:
        fr = HostAddForm(
        initial= {'protocol_type':'SSH',}
        )
    return render_to_response('hostadd.html',locals())

def hostadds(request):
    username = request.session.get('username',None)
    if request.method == "POST":
        fr = HostAddsForm(request.POST)
        if fr.is_valid():
            info = fr.cleaned_data['info']
            N = len(info.split('|'))
            for i in range(int(N)):
                IP.objects.create(
                ip = info.split('|')[i].strip().split()[0],
                port = info.split('|')[i].strip().split()[1],
                user = info.split('|')[i].strip().split()[2],
                passwd = info.split('|')[i].strip().split()[3],
                protocol_type = info.split('|')[i].strip().split()[4],
                group = info.split('|')[i].strip().split()[5],
                alias = info.split('|')[i].strip().split()[6],
                )
            msg = '主机添加成功！'
            return render_to_response('msg.html',locals())
            
                

            return HttpResponse('0')
    else:
        fr = HostAddsForm()
    return render_to_response('hostadds.html',locals())

def hostdel(request,IP_id):
    username = request.session.get('username',None)
    IP.objects.filter(id=IP_id).delete()
    return HttpResponseRedirect('/host.html')

def hostupdate(request,IP_id):
    username = request.session.get('username',None)
    group_list = IpGroup.objects.all()
    ipinfo = IP.objects.get(id=IP_id)
    if request.method == "POST":
        fr = HostAddForm(request.POST)
        if fr.is_valid():
            IP.objects.filter(id=IP_id).update(
            ip = fr.cleaned_data['ip'],
            port = fr.cleaned_data['port'],
            user = fr.cleaned_data['user'],
            passwd = request.POST.get('passwd'),
            protocol_type = fr.cleaned_data['protocol_type'],
            hostname = fr.cleaned_data['hostname'],
            system = fr.cleaned_data['system'],
            server_models = fr.cleaned_data['server_models'],
            cpu = fr.cleaned_data['cpu'],
            cpumun = fr.cleaned_data['cpumun'],
            hmem = fr.cleaned_data['hmem'],
            vmem = fr.cleaned_data['vmem'],
            disk = fr.cleaned_data['disk'],
            alias = fr.cleaned_data['alias'],
            group = request.POST.get(u'select','末分组'),
            )
            msg = '主机修改成功！'
            return render_to_response('msg.html',locals())
            
    else:
        mypasswd = ipinfo.passwd
        fr = HostAddForm(
        initial= {
        'ip':ipinfo.ip,
        'port':ipinfo.port,
        'user':ipinfo.user,
        'protocol_type':ipinfo.protocol_type,
        'hostname':ipinfo.hostname,
        'system':ipinfo.system,
        'server_models':ipinfo.server_models,
        'cpu':ipinfo.cpu,
        'cpumun':ipinfo.cpumun,
        'hmem':ipinfo.hmem,
        'vmem':ipinfo.vmem,
        'disk':ipinfo.disk,
        'alias':ipinfo.alias,
        'group':ipinfo.group,
        }
        )
        group2 = ipinfo.group  #把组名传递给模板中的select，可默认选中所属分组
        
    return render_to_response('hostupdate.html',locals())
    


def groupadd(request):
    username = request.session.get('username',None)
    group_list = IpGroup.objects.all()
    if request.method == "POST":
        fr = GroupAddForm(request.POST)
        if fr.is_valid():
            IpGroup.objects.create(
            group_name = fr.cleaned_data['group_name'],
            )
            return HttpResponseRedirect('/groupadd.html')
    else:
        fr = GroupAddForm()
    return render_to_response('groupadd.html',locals())

def groupdel(request,G_id):
    username = request.session.get('username',None)
    IpGroup.objects.filter(id=G_id).delete()
    return HttpResponseRedirect('/groupadd.html')

def infoupdate(request,ID):
    username = request.session.get('username',None)
    import paramiko
    ipaddr =  IP.objects.get(id=ID).ip
    USERNAME = IP.objects.get(id=ID).user
    PORT = IP.objects.get(id=ID).port
    PASSWORD = IP.objects.get(id=ID).passwd
    PROTOCOL = IP.objects.get(id=ID).protocol_type
    client = paramiko.SSHClient()
    client.load_system_host_keys()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    try:
        if PROTOCOL == 'KEY':
            pkey_file = '/root/.ssh/id_rsa'          
            key = paramiko.RSAKey.from_private_key_file(pkey_file)               
            client.connect(ipaddr,int(PORT),USERNAME,pkey=key,timeout=5) 
        else:                                                        
            client.connect(ipaddr,int(PORT),USERNAME,PASSWORD,timeout=5)
    except:
        return HttpResponse('0')
    CMDLIST = [
    "hostname",
    "free -m|sed -n 2p|awk '{print $2}'",
    "free -m|sed -n 4p|awk '{print $2}'",
    "uname -v 2>&1 |awk -F '[- ]' '{print $2}'",
    "dmidecode | grep 'Product Name'  |sed -n '1p' |awk -F ': ' '{print $2}'",
    "/bin/cat /proc/cpuinfo|grep -c 'processor'",
    "fdisk -l |grep 'Disk /dev/'|awk '{a+=$3}END{print a}'",
    "/bin/cat /proc/cpuinfo |grep 'model name'|uniq|awk -F ':' '{print $2}'"
    ]
    data_list = []
    for CMD in CMDLIST:
        stdin, stdout, stderr = client.exec_command(CMD)
        DATA = stdout.read()
        data_list.append(DATA)
    IP.objects.filter(id = ID).update(
        hostname = data_list[0],
        hmem = data_list[1],
        vmem = data_list[2],
        system = data_list[3],
        server_models = data_list[4],
        cpumun = data_list[5],
        disk = data_list[6],
        cpu = data_list[7],
        
    )
    return HttpResponseRedirect('/host.html')
#    return HttpResponse('1')
    
def cmd(request):
    '''执行单机命令'''
    username = request.session.get('username',None)
    import paramiko
    iplist = IP.objects.all()
    if request.method == "POST":
        import paramiko
        ID = request.POST.get('select')
        if ID == "-1":
            return HttpResponse("请选择ip")
        ipaddr =  IP.objects.get(id=ID).ip
        USERNAME = IP.objects.get(id=ID).user
        PORT = IP.objects.get(id=ID).port
        PASSWORD = IP.objects.get(id=ID).passwd
        PROTOCOL = IP.objects.get(id=ID).protocol_type
        hostname = IP.objects.get(id=ID).hostname
        client = paramiko.SSHClient()
        client.load_system_host_keys()
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        try:
            if PROTOCOL == 'KEY':
                pkey_file = '/root/.ssh/id_rsa'          
                key = paramiko.RSAKey.from_private_key_file(pkey_file)               
                client.connect(ipaddr,int(PORT),USERNAME,pkey=key,timeout=5) 
            else:                                                        
                client.connect(ipaddr,int(PORT),USERNAME,PASSWORD,timeout=5)
        except:
            return HttpResponse('连接失败')
        CMD = request.POST.get('cmd')
        stdin, stdout, stderr = client.exec_command(CMD)
        DATA = stdout.readlines()
        RDATA = []
        for line in DATA:
            RDATA.append(line)
        return render_to_response('cmd.html',locals())
    return render_to_response('cmd.html',locals())

def saltcmd(request):
    username = request.session.get('username',None)
    if request.method == "POST":
        fr = SaltCmdForm(request.POST)
        if fr.is_valid():
            saltcmd = request.POST.get('saltcmd')
            import subprocess
            DATA = subprocess.check_output(saltcmd,shell=True)
            RDATA = []
            for i in DATA.split('\n'):
                RDATA.append(i)
            return render_to_response('saltcmd.html',locals())
    else:
        fr = SaltCmdForm()
    return render_to_response('saltcmd.html',locals())        
            
            
            
            
def morecmd(request):
    '''批量执行命令'''
    username = request.session.get('username',None)
    if request.method == "POST":
        fr = MoreCmdForm(request.POST)
        if fr.is_valid():
            Match = request.POST.get('select')
            keyword = fr.cleaned_data['keyword']
            kend = keyword[-1]    #获取关键字中的最后一个字符
            print kend
            CMD = fr.cleaned_data['morecmd']
            if Match == 'group':
                iplist = IP.objects.filter(group__contains=keyword)
            elif Match == 'alias':
                if kend == '*':    #如果最后一个字符等于'*'，则用模糊匹配关键字，
                    iplist = IP.objects.filter(alias__contains=keyword[0:-1])  #keyword[0:-1]获取除最后一个字符的字符串
                else:
                    iplist = IP.objects.filter(alias=keyword)     
            else:
                iplist = IP.objects.all()
            IPid = []
            for ip  in iplist:
                IPid.append(ip.ip)
         
            import os
            IP_list = ' '.join(IPid)
            Run = "/python/umework/umwork/scripts/multiprocessingcmd.py '%s' '%s'" % (IP_list,CMD)
            os.system(Run)
            RDATA = open('result.txt','r').readlines()
            return render_to_response('morecmd.html',locals())
    else:
        fr = MoreCmdForm()
    return render_to_response('morecmd.html',locals())



def install(request):
    '''服务安装'''
    username = request.session.get('username',None)
    iplist = IP.objects.all()
    server_list = AddServer.objects.all()
    mserver_list = MServer.objects.all()
    if request.method == "POST":
        if request.POST.has_key('install'):
            import paramiko
            ID = int(request.POST.get('select'))  #这里ID转变整形，主要是为了模板select中，对option子项进行比较，
            PATH = request.POST.get('select2')
            ipaddr =  IP.objects.get(id=ID).ip
            USERNAME = IP.objects.get(id=ID).user
            PORT = IP.objects.get(id=ID).port
            PASSWORD = IP.objects.get(id=ID).passwd
            PROTOCOL = IP.objects.get(id=ID).protocol_type
            client = paramiko.SSHClient()
            client.load_system_host_keys()
            client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            try:
                if PROTOCOL == 'KEY':
                    pkey_file = '/root/.ssh/id_rsa'          
                    key = paramiko.RSAKey.from_private_key_file(pkey_file)               
                    client.connect(ipaddr,int(PORT),USERNAME,pkey=key,timeout=5) 
                else:                                                        
                    client.connect(ipaddr,int(PORT),USERNAME,PASSWORD,timeout=5)
            except:
                return HttpResponse('连接失败')
            CMD = 'wget -O - http://www.linuxyw.com/%s |sh' % PATH
            stdin, stdout, stderr = client.exec_command(CMD)
            DATA = stdout.readlines()
            return render_to_response('install.html',locals())
        if request.POST.has_key('server'):
            import paramiko
            ID = int(request.POST.get('select3'))
            SID = int(request.POST.get('select4'))
            SM = request.POST.get('select5')
            print SM,SID
            if SM == '1':  
            	MCMD = MServer.objects.get(id = SID).Mstart
            elif SM == '2':
            	MCMD = MServer.objects.get(id = SID).Mrestart
            elif SM == '3':
            	MCMD = MServer.objects.get(id = SID).Mstop
            ipaddr =  IP.objects.get(id=ID).ip
            USERNAME = IP.objects.get(id=ID).user
            PORT = IP.objects.get(id=ID).port
            PASSWORD = IP.objects.get(id=ID).passwd
            PROTOCOL = IP.objects.get(id=ID).protocol_type
            client = paramiko.SSHClient()
            client.load_system_host_keys()
            client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            try:
            	if PROTOCOL == 'KEY':
            		pkey_file = '/root/.ssh/id_rsa'          
            		key = paramiko.RSAKey.from_private_key_file(pkey_file)               
            		client.connect(ipaddr,int(PORT),USERNAME,pkey=key,timeout=5) 
            	else:                                                        
            		client.connect(ipaddr,int(PORT),USERNAME,PASSWORD,timeout=5)
            except:
            	return HttpResponse('连接失败')
            stdin, stdout, stderr = client.exec_command(MCMD)
            MDATA = stdout.readlines()
            
            
            return render_to_response('install.html',locals())      
    return render_to_response('install.html',locals())
    

def addinstall(request):
    '''添加可安装的服务名'''
    username = request.session.get('username',None)
    server_list = AddServer.objects.all()
    if request.method == "POST":
        fr = AddServerForm(request.POST)
        if fr.is_valid():
            AddServer.objects.create(
            sname = fr.cleaned_data['sname'],
            spath = fr.cleaned_data['spath'],
            )
            return HttpResponseRedirect('/addinstall.html')
    else:
        fr = AddServerForm()
    return render_to_response('addinstall.html',locals())
    
def installdel(request,ID):
    '''删除服务名'''
    username = request.session.get('username',None)
    AddServer.objects.filter(id=ID).delete()
    return HttpResponseRedirect('/addinstall.html')
    



def addmserver(request):
    username = request.session.get('username',None)
    '''添加服务管理项'''
    server_list = MServer.objects.all()
    if request.method == "POST":
        fr = MServerForm(request.POST)
        if fr.is_valid():
            MServer.objects.create(
            Mname = fr.cleaned_data['mname'],
            Mstart = fr.cleaned_data['mstart'],
            Mrestart = fr.cleaned_data['mrestart'],
            Mstop = fr.cleaned_data['mstop'],
            )
            return HttpResponseRedirect('/addmserver.html')
    else:
        fr = MServerForm()
    return render_to_response('addmserver.html',locals())

def mserverdel(request,ID):
    username = request.session.get('username',None)
    '''删除服务管理项'''
    MServer.objects.filter(id=ID).delete()
    return HttpResponseRedirect('/addmserver.html')

def mserverstart(request,ID,CID):
    username = request.session.get('username',None)
    CMD = MServer.objects.get(id = CID).Mstart
    ipaddr =  IP.objects.get(id=ID).ip
    USERNAME = IP.objects.get(id=ID).user
    PORT = IP.objects.get(id=ID).port
    PASSWORD = IP.objects.get(id=ID).passwd
    PROTOCOL = IP.objects.get(id=ID).protocol_type
    client = paramiko.SSHClient()
    client.load_system_host_keys()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    try:
        if PROTOCOL == 'KEY':
            pkey_file = '/root/.ssh/id_rsa'          
            key = paramiko.RSAKey.from_private_key_file(pkey_file)               
            client.connect(ipaddr,int(PORT),USERNAME,pkey=key,timeout=5) 
        else:                                                        
            client.connect(ipaddr,int(PORT),USERNAME,PASSWORD,timeout=5)
    except:
        return HttpResponse('连接失败')
    stdin, stdout, stderr = client.exec_command(CMD)
    DATA = stdout.readlines()
    return render_to_response('install.html',locals())
    
    
    
def mserverrestart(request,ID,CMD):
    username = request.session.get('username',None)
    CMD = MServer.objects.get(id = CID).Mrestart
    ipaddr =  IP.objects.get(id=ID).ip
    USERNAME = IP.objects.get(id=ID).user
    PORT = IP.objects.get(id=ID).port
    PASSWORD = IP.objects.get(id=ID).passwd
    PROTOCOL = IP.objects.get(id=ID).protocol_type
    client = paramiko.SSHClient()
    client.load_system_host_keys()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    try:
        if PROTOCOL == 'KEY':
            pkey_file = '/root/.ssh/id_rsa'          
            key = paramiko.RSAKey.from_private_key_file(pkey_file)               
            client.connect(ipaddr,int(PORT),USERNAME,pkey=key,timeout=5) 
        else:                                                        
            client.connect(ipaddr,int(PORT),USERNAME,PASSWORD,timeout=5)
    except:
        return HttpResponse('连接失败')
    stdin, stdout, stderr = client.exec_command(CMD)
    DATA = stdout.readlines()
    return render_to_response('install.html',locals())
    
def mserverstop(request,ID,CMD):
    username = request.session.get('username',None)
    CMD = MServer.objects.get(id = CID).Mstop
    ipaddr =  IP.objects.get(id=ID).ip
    USERNAME = IP.objects.get(id=ID).user
    PORT = IP.objects.get(id=ID).port
    PASSWORD = IP.objects.get(id=ID).passwd
    PROTOCOL = IP.objects.get(id=ID).protocol_type
    client = paramiko.SSHClient()
    client.load_system_host_keys()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    try:
        if PROTOCOL == 'KEY':
            pkey_file = '/root/.ssh/id_rsa'          
            key = paramiko.RSAKey.from_private_key_file(pkey_file)               
            client.connect(ipaddr,int(PORT),USERNAME,pkey=key,timeout=5) 
        else:                                                        
            client.connect(ipaddr,int(PORT),USERNAME,PASSWORD,timeout=5)
    except:
        return HttpResponse('连接失败')
    stdin, stdout, stderr = client.exec_command(CMD)
    DATA = stdout.readlines()
    return render_to_response('install.html',locals())
    
def codeup(request):
    username = request.session.get('username',None)
    wiplist = Codeserver.objects.all()    #获取数据库Codeserver表所有内容
    if request.method == "POST":     #如果是从POST方法提交的，则进行下面代码，否则，请看此函数最后相对应的else
        fr = CodeupForm(request.POST,request.FILES)   #把表单forms.py中的内容赋予fr
        if fr.is_valid():   #判断此次提交的fr表单是否有效
            try:
                File = request.FILES.get('File', None)  #把获取到的上传文件赋予File
                FileName = '/python/umework/umwork/software/%s'% File.name   #FileName是WEB服务器上传的路径和文件名，这个文件名也就是刚才从表单获取到的文件名
                with open(FileName ,'wb+') as of:   #把获取到的文件保存到WEB服务器中
                    for chunk in File.chunks():   #在这里使用chunks()，是为了节约内存消耗，但这需要用循环的方法去保存，因为是切片保存的，当然也可以用read()来获取文件和保存文件，但会特别占用系统内存
                        of.write(chunk)          #保存到服务器
                import paramiko
                client = paramiko.SSHClient()
                client.load_system_host_keys()
                client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
                Ip = request.POST.get('select1')
                
                PATH = Codeserver.objects.get(ip=Ip).path
                BackupPath = Codeserver.objects.get(ip=Ip).backuppath
                BackDir = Codeserver.objects.get(ip=Ip).backdir
                import time
                NewTime = time.strftime('%Y-%m-%d-%H-%M',time.localtime(time.time()))
                DPATH = '%s/%s'%(PATH,File.name)
                
                USERNAME = IP.objects.get(ip=Ip).user
                PORT = IP.objects.get(ip=Ip).port
                PASSWORD = IP.objects.get(ip=Ip).passwd
                PROTOCOL = IP.objects.get(ip=Ip).protocol_type

                try:
                    t = paramiko.Transport((Ip,int(PORT)))
                    t.connect(username = USERNAME,password = PASSWORD)
                    sftp = paramiko.SFTPClient.from_transport(t)
                    sftp.put(FileName,DPATH)
                    client.connect(Ip,int(PORT),USERNAME,PASSWORD,timeout=5)
                    
                    if os.path.isdir(BackupPath):
                        os.makedirs(BackupPath)
                    CMD = [
                    'cd %s && tar zcf %s.tar.gz %s'%(PATH,NewTime,BackDir),
                    'if [ ! -d %s ];then mkdir -p %s; fi'%(BackupPath,BackupPath),
                    'mv -f %s %s'%(DPATH,BackupPath),
                    'unzip -oqu %s -d %s'%(DPATH,PATH),
                    'rm -f %s'%DPATH
                    ]
                    for i in CMD:
                        stdin, stdout, stderr = client.exec_command(i)
                    client.close()
                except:
                    return HttpResponse('连接失败')             
                return HttpResponseRedirect('/codeup.html')
            except:
                return HttpResponse('文件上传错误')
    else:
        fr = CodeupForm()
    return render_to_response('codeup.html',locals())

def addwebserver(request):
    username = request.session.get('username',None)
    wiplist = Codeserver.objects.all()
    if request.method == "POST":
        fr = CodeserverForm(request.POST)
        if fr.is_valid():
            Codeserver.objects.create(
            ip = fr.cleaned_data['ip'],
            backuppath = fr.cleaned_data['backuppath'],
            backdir = fr.cleaned_data['backdir'],
            path = fr.cleaned_data['path'],
            )
        return HttpResponseRedirect('/addwebserver.html')
    else:
        fr = CodeserverForm()
    return render_to_response('addwebserver.html',locals())

def webserverdel(request,ID):
    '''删除WEB服务器'''
    username = request.session.get('username',None)
    Codeserver.objects.filter(id=ID).delete()
    return HttpResponseRedirect('/addwebserver.html')
    
    
def useradd(request):
    '''添加用户'''
    username = request.session.get('username',None)
    userpermissions = User.objects.get(name = username).permissions
    departments = Department.objects.all()
    usergroups = Usergroup.objects.all()
    if request.method == "POST":
        fr = UserForm(request.POST)
        if fr.is_valid():
            User.objects.create(
            user = fr.cleaned_data['user'],
            passwd = fr.cleaned_data['passwd'],
            name = fr.cleaned_data['name'],
            post = request.POST.get(u'select1'),
            phone = fr.cleaned_data['phone'],
            email = fr.cleaned_data['email'],
            qq = fr.cleaned_data['qq'],
            permissions = request.POST.get(u'select2','-1'),  #使用此request后，在forms.py中，不可出现此字段，否则会出错
            )        
            msg = '用户添加成功！'    
            return render_to_response('msg.html',locals()) #跳转到msg.html页面中，并传递msg变量过去
            
    else:
        fr = UserForm()
    return render_to_response('useradd.html',locals())

def userinfo(request):
    username = request.session.get('username',None)
    myid = User.objects.get(name = username).id
    userpermissions = User.objects.get(name = username).permissions
    '''用户信息'''
    userinfo = User.objects.all()
    return render_to_response('userinfo.html',locals())


def userdel(request,ID):
    '''删除用户'''
    username = request.session.get('username',None)
    userpermissions = User.objects.get(name = username).permissions
    if userpermissions == u'运维经理':
        User.objects.filter(id = ID).delete()
        return HttpResponseRedirect('/userinfo.html') 
    else:
        return HttpResponse('你无权删除')
    
def usermod(request,ID):
    username = request.session.get('username',None)
    userpermissions = User.objects.get(name = username).permissions
    myid = int(User.objects.get(name = username).id)  #获取从session中得到的用户的ID号,这里必须用int()把ID转为整形，因为默认传递过来是字符型
    urlid = int(ID)         #此变量将传递给前端模板，将与myid进行对比，如果相等，则有权修改自己的密码
    print myid,urlid
    departments = Department.objects.all()
    usergroups = Usergroup.objects.all()
    myself = User.objects.get(id = ID)
    if request.method == "POST":
        fr = UserForm(request.POST)
        if fr.is_valid():
            User.objects.filter(id = ID).update(
            user = fr.cleaned_data['user'],
            passwd = request.POST.get('passwd'),
            name = fr.cleaned_data['name'],
            post = request.POST.get(u'select1'),
            phone = fr.cleaned_data['phone'],
            email = fr.cleaned_data['email'],
            qq = fr.cleaned_data['qq'],
            permissions = request.POST.get(u'select2','-1'),  #使用此request后，在forms.py中，不可出现此字段，否则会出错
            ) 
            msg = '用户修改成功！'    
            return render_to_response('msg.html',locals()) #跳转到msg.html页面中，并传递msg变量过去
    else:
        mypass = User.objects.get(id = ID).passwd
        fr = UserForm(
        initial= {
        'user':myself.user,
        'name':myself.name,
        'phone':myself.phone,
        'email':myself.email,
        'qq':myself.qq,
        }
        )
        select1=myself.post #把组名传递给模板中的select1，可默认选中所属部门
        select2=myself.permissions #把组名传递给模板中的select2，可默认选中所属职位
    return render_to_response('usermod.html',locals())

def userpasswd(request,ID):
    username = request.session.get('username',None)
    myid = int(User.objects.get(name = username).id)
    userpermissions = User.objects.get(name = username).permissions
    print userpermissions
    urlid = int(ID)
    if myid == urlid or userpermissions == u'运维经理':
        if request.method == "POST":
            OldPasswd = request.POST.get('oldpasswd')
            New1Passwd = request.POST.get('new1passwd')
            New2Passwd = request.POST.get('new2passwd')
            print 'old:',OldPasswd,
            print 'new:',New1Passwd,New2Passwd
            user = User.objects.filter(name=username,passwd=OldPasswd)
            print 'user:',user
            if user:
                if New1Passwd:
                    if New1Passwd == New2Passwd:
                        User.objects.filter(id = myid).update(
                        passwd = New1Passwd,
                        )
                        msg = "密码修改成功！"
                        return render_to_response('msg.html',locals())
                    else:
                        msg = "2次输入的新密码不一致！"
                        return render_to_response('msg.html',locals())
                else:
                    msg = "请输入新密码！"
                    return render_to_response('msg.html',locals())
            else:
                msg = "旧密码不正确！"
                return render_to_response('msg.html',locals())
    else:
        msg = "你无权修改别人密码"
        return render_to_response('msg.html',locals())
    return render_to_response('userpasswd.html',locals())
    
def department(request):
    username = request.session.get('username',None)
    userpermissions = User.objects.get(name = username).permissions
    departments = Department.objects.all()
    if request.method == "POST":
        fr = DepartmentForm(request.POST)
        if fr.is_valid():
            Department.objects.create(
            name = fr.cleaned_data['name']
            )
        msg = '部门添加成功'
        return render_to_response('msg.html',locals())
    else:
        fr = DepartmentForm()
    return render_to_response('department.html',locals())

def usergroup(request):
    username = request.session.get('username',None)
    userpermissions = User.objects.get(name = username).permissions
    usergroups = Usergroup.objects.all()
    if request.method == "POST":
        fr = UsergroupForm(request.POST)
        if fr.is_valid():
            Usergroup.objects.create(
            name = fr.cleaned_data['name']
            )
        msg = '职位添加成功'
        return render_to_response('msg.html',locals())
    else:
        fr = UsergroupForm()
    return render_to_response('usergroup.html',locals())

def taskadd(request):
    username = request.session.get('username',None)
    userall = User.objects.all()
    if request.method == "POST":
        fr = TaskForm(request.POST)
        if fr.is_valid():
            Task.objects.create(
            task_name = request.POST.get('taskname'),
            from_name = username,
            to_name = request.POST.get(u'select2','-1'),
            content = request.POST.get('content'),
            completion_time = request.POST.get('time'),
            urgent_status = request.POST.get(u'select3','-1'),
            )
            '''刚才上面我们往Task表中插入了一条记录，下面我们将要获取到这个记录的ID号，把这个ID保存到Myssage表中，在消息中心url到具体页面时要用的到'''
            Message.objects.create(
            taskid = Task.objects.order_by("-id")[0].id,  #获取Task表中最新记录的id值，通过order_by("-id")按id倒序用[0]来获取最新的一条记录，然后用.id取id值
            fromname = username,
            toname = request.POST.get(u'select2','-1'),
            title = request.POST.get('taskname'),
            )
            Email = User.objects.get( name = request.POST.get(u'select2')).email
            Econtent = request.POST.get('content')
            Esub = request.POST.get('taskname')
            from multiprocessing import Process
            p = Process(target=send_mail,args=(Email,Esub,Econtent,))  #使用multiprocessing单进程模式，发送EMail，这样可提交后不管，只接返回WEB，不需等待发送完EMAIL才返回WEB
            p.start() 
            return HttpResponseRedirect('/taskinfo.html')
    else:
        fr = TaskForm()
    return render_to_response('taskadd.html',locals())

def taskinfo(request):
    taskinfo = Task.objects.all().order_by('-id')
    username = request.session.get('username',None)
    userpermissions = User.objects.get(name = username).permissions
    return render_to_response('taskinfo.html',locals())

def taskdel(request,ID):
    '''删除任务'''
    username = request.session.get('username',None)
    userpermissions = User.objects.get(name = username).permissions
    if userpermissions == u'运维经理':
        Task.objects.filter(id = ID).delete()
        return HttpResponseRedirect('/taskinfo.html')
    else:
        return HttpResponse('你无权删除')

def login(request):
    username = request.session.get('username',None)
    Tasklist = Task.objects.order_by("-id")[0:10]
    if request.method == "POST":
        fr = loginForm(request.POST)
        if fr.is_valid():
            username = fr.cleaned_data['username']
            password = fr.cleaned_data['password']
            name = User.objects.get(user = username).name
            user = User.objects.filter(user=username,passwd=password)  #数据过滤，这里如果都匹配则返回值,
            if user:   #判断这个是否有效值
                request.session['username'] = name
                return HttpResponseRedirect("/")
            else:  #无效
                return HttpResponseRedirect("/login.html")
    else:
        fr = loginForm()
    return render_to_response('login.html',locals())

def logout(request):
    del request.session['username']
    return HttpResponseRedirect("/login.html")

def myhome(request):
    username = request.session.get('username',None)
    userpermissions = User.objects.get(name = username).permissions
    mytask = Task.objects.filter(to_name = username).order_by('-id')
    myid = User.objects.get(name = username)
    mymessage = Message.objects.filter(toname = username,status = "0") 
    return render_to_response('myhome.html',locals())

def ireleasetask(request):
    username = request.session.get('username',None)
    userpermissions = User.objects.get(name = username).permissions
    mytask = Task.objects.filter(from_name = username).order_by('-id')
    return render_to_response('ireleasetask.html',locals())

def mytask(request,ID):
    username = request.session.get('username',None)
    TID = Task.objects.get(id=ID)
    mycomments = TaskComments.objects.filter(taskid = ID)
    if request.method == "POST":
        if request.POST.has_key('accept'):
            Task.objects.filter(id=ID).update(
            task_status="1"
            )
            TaskComments.objects.create(
            taskid = ID,
            fromname = username,
            toname = Task.objects.get(id=ID).from_name,
            content = '%s 接受了任务！'%username.encode('utf-8')
            )
            return HttpResponseRedirect("/mytask/%s.html"%ID)
        elif request.POST.has_key('ok'):
            Task.objects.filter(id=ID).update(
            task_status="2"            
            )
            TaskComments.objects.create(
            taskid = ID,
            fromname = username,
            toname = Task.objects.get(id=ID).from_name,
            content = '%s 完成了任务！'%username.encode('utf-8')
            )
            return HttpResponseRedirect("/mytask/%s.html"%ID)
        elif request.POST.has_key('comments'):
            TaskComments.objects.create(
            taskid = ID,
            fromname = username,
            toname = Task.objects.get(id=ID).from_name,
            content = request.POST.get('content'),
            )
            return HttpResponseRedirect("/mytask/%s.html"%ID)
    return render_to_response('mytask.html',locals())

def mymessage(request):
    username = request.session.get('username',None)
    message = Message.objects.filter(toname=username)
    return render_to_response('mymessage.html',locals())


def config(request):
    '''全局邮件配置'''
    username = request.session.get('username',None)  #获取用session的值，即为获取用户名，我们在登陆的时候，赋于了这个值，请看login
    userpermissions = User.objects.get(name = username).permissions
    try:
        Configall = Config.objects.order_by("-id")[0]  #取表里面的最后一条数据 
    except:
        Configall =  False
    if request.method == "POST":    #假如request的方法为POST
        fr = ConfigForm(request.POST)
        if Configall != False:  
            if fr.is_valid():
                Config.objects.filter(id = Configall.id).update(
                mailsmtp = request.POST.get('mailsmtp'),   #获取模板表单input中name=mailsmtp的值
                mailuser = request.POST.get('mailuser'),   #以下相同语句作用同上
                mailpass = request.POST.get('mailpass'),
                mailfrom = request.POST.get('mailfrom'),
                )
            return HttpResponseRedirect('/config.html')
        else:   #如果是空表，那变量正为假，就往表里写入数据
            if fr.is_valid():
                Config.objects.create(
                mailsmtp = request.POST.get('mailsmtp'),
                mailuser = request.POST.get('mailuser'),
                mailpass = request.POST.get('mailpass'),
                mailfrom = request.POST.get('mailfrom'),
                )
            return HttpResponseRedirect('/config.html')
    elif Configall != False:
        mailsmtp = Configall.mailsmtp
        mailuser = Configall.mailuser
        mailpass = Configall.mailpass
        mailfrom = Configall.mailfrom
    return render_to_response('config.html',locals())


def ke_upload_view(request):  
    '''富文本编辑器文件上传'''
    import datetime,json,time
    ext_allowed = {}  
    ext_allowed["image"] = ['gif', 'jpg', 'jpeg', 'png']  
    ext_allowed["flash"] = ["swf", "flv"]  
    ext_allowed["media"] = ["swf", "flv", "mp3", "wav", "wma", "wmv", "mid", "avi", "mpg", "asf", "rm", "rmvb"]  
    ext_allowed["file"] = ["doc", "docx", "xls", "xlsx", "ppt", "htm", "html", "txt", "zip", "rar", "gz" , "bz2"]  
      
    max_size = 1000000  
    today = datetime.datetime.today()  
    dir_name = request.GET["dir"]  
    save_dir = '/upload/' + dir_name + '/%d/%d/%d/' % (today.year, today.month, today.day)  #保存文件的命名规则
    save_path = settings.MEDIA_ROOT + save_dir  #配置文件保存路径，这里也跟settings.py中的MEDIA_ROOT有关，当然这里也可以自由设置，如绝对路径 
    save_url =  '/bootstrap' + save_dir      #配置文件读取路径，这里，还要看settings.py中的MEDIA_ROOT配置，跟这里有关的。

    if request.method == 'POST':  
        file_content = request.FILES['imgFile']  

        if not file_content.name:  
            return HttpResponse(json.dumps(  
                { 'error': 1, 'message': u'请选择要上传的文件' }  
            ))  
              
        ext = file_content.name.split('.').pop()  
          
        if ext not in ext_allowed[dir_name]:  
            return HttpResponse(json.dumps(  
                { 'error': 1, 'message': u'请上传后缀为%s的文件' %  ext_allowed[dir_name]}  
            ))  

        if file_content.size > max_size:  
            return HttpResponse(json.dumps(  
                { 'error': 1, 'message': u'上传的文件大小不能超过10MB'}  
            ))  

        if not os.path.isdir(save_path):  
            os.makedirs(save_path)  

        new_file = '%s.%s' % (int(time.time()), ext)  

        destination = open(save_path+new_file, 'wb+')  
        for chunk in file_content.chunks():  
            destination.write(chunk)  
        destination.close()  

        return HttpResponse(json.dumps(  
                { 'error': 0, 'url': save_url+new_file}  
        ))  

def msg(request):
    return render_to_response('msg.html',locals())



    
    
    